<template>
  <div class="table-page">
    <!-- <a-form label-align="right" layout="inline" auto-label-width :model="listParams" size="small" class="form my-10">
      <a-form-item field="keyword" hide-label>
        <a-input v-model="listParams.keyword" placeholder="输入关键字检索" @press-enter="changeCurrent(1)"></a-input>
      </a-form-item>
      <a-form-item field="categoryId" hide-label>
        <a-space>
          <a-button type="primary" size="small" @click="changeCurrent(1)">
            <template #icon>
              <icon-search />
            </template>
            <template #default>查询</template>
          </a-button>
          <a-button size="small" @click="onResetSearch">
            <template #icon>
              <icon-sync />
            </template>
            <template #default>重置</template>
          </a-button>
        </a-space>
      </a-form-item>
    </a-form> -->
    <GiTable
      row-key="id"
      id="appNotice"
      v-model:columns="columns"
      :loading="loading"
      :data="tableData"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :row-selection="{ type: 'checkbox', showCheckedAll: true }"
      v-model:selectedKeys="selectedKeys"
      :pagination="pagination"
      @sorter-change="onSorterChange"
      @refresh="getTableData"
    >
      <template #custom-extra>
        <a-button type="primary" size="small" @click="onAddOrEdit(false)">
          <template #icon><icon-plus /></template>
          <span>新增</span>
        </a-button>
        <a-button v-if="selectedKeys.length > 0" type="primary" size="small" @click="onDeleteBatch(false)">
          <template #icon><icon-delete /></template>
          <span>批量删除</span>
        </a-button>
      </template>
      <template #isShow="{ record }">
        <a-switch
          :checked-value="1"
          :unchecked-value="0"
          v-model="record.isShow"
          :before-change="handleChangeStatus.bind(null, record, 'isShow')"
        ></a-switch>
      </template>
      <template #action="{ record }">
        <a-button type="text" size="small" @click="onAddOrEdit(record)"> 编辑 </a-button>
        <a-button type="text" size="small" @click="onDeleteBatch(record.id)"> 删除 </a-button>
      </template>
    </GiTable>
  </div>
</template>

<script setup>
import { Modal, Message } from '@arco-design/web-vue'
import { usePagination } from '@/hooks'
import { announcementList, announcementDelete, announcementEdit } from '@/apis'
import ImgHoverPreview from '@/components/ImgHoverPreview/index.vue'
import $bus from '@/utils/bus'

defineOptions({ name: 'appNotice' })

const columns = ref([
  {
    title: '标题',
    width: 200,
    dataIndex: 'title'
  },
  {
    title: '图片',
    width: 80,
    render: (data) => {
      const url = data.record.pic
      return h(ImgHoverPreview, { url, width: 50 })
    }
  },
  {
    title: '点击量',
    width: 90,
    dataIndex: 'clickCount'
  },
  {
    title: '状态',
    width: 90,
    slotName: 'isShow'
  },
  {
    title: '创建时间',
    width: 180,
    dataIndex: 'createAt',
    render: ({ record }) => {
      return record.createAt || '--'
    }
  },
  {
    title: '操作',
    width: 220,
    fixed: 'right',
    align: 'center',
    slotName: 'action'
  }
])

const router = useRouter()
const loading = ref(false)
const tableData = ref([])
const selectedKeys = ref([])

const { pagination, setTotal } = usePagination(() => getTableData(), { defaultPageSize: 10 })

const listParams = reactive({
  page: 1,
  pageSize: 10,
  keyword: undefined,
  isShow: undefined
})

// 获取列表数据
const getTableData = async () => {
  try {
    loading.value = true
    listParams.page = pagination.current
    listParams.pageSize = pagination.pageSize
    const res = await announcementList(listParams)
    tableData.value = res.data.list
    setTotal(res?.data?.meta?.pagination?.total || 0)
  } finally {
    loading.value = false
  }
}
getTableData()

// 添加/编辑
const onAddOrEdit = (item) => {
  router.push({
    name: 'appNoticeEdit',
    query: { id: item?.id },
    state: item ? { item: JSON.stringify(item) } : undefined
  })
}

// 表格页码改变
const changeCurrent = (e) => {
  pagination.current = listParams.page = e
  getTableData()
}

//升降序发生改变
const onSorterChange = (dataIndex, direction) => {
  listParams.orderBy = direction ? (direction === 'ascend' ? 'asc' : 'desc') : undefined
  listParams.sort = listParams.orderBy ? dataIndex : undefined
  changeCurrent(1)
}

// 重置筛选查询
const onResetSearch = () => {
  listParams.keyword = undefined
  changeCurrent(1)
}

// 删除数据
const onDeleteBatch = (id) => {
  Modal.warning({
    title: '提示',
    content: '是否确认删除？',
    hideCancel: false,
    onOk: () => {
      loading.value = true
      const ids = id ? [id] : selectedKeys.value
      announcementDelete({ ids: ids.join(',') })
        .then(() => {
          selectedKeys.value = []
          Message.success('删除成功')
          getTableData()
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}

// 改变列表中的切换按钮状态
const handleChangeStatus = async (record, str, newValue) => {
  await new Promise((resolve, reject) => {
    announcementEdit({ ...record, [str]: newValue })
      .then(() => {
        Message.success('操作成功')
        getTableData()
        resolve(true)
      })
      .catch(() => {
        reject()
      })
  })
}

onMounted(() => {
  $bus.on('appNotice', () => {
    getTableData()
  })
})

onUnmounted(() => {
  $bus.off('appNotice')
})
</script>
